package com.iretailer.report.web.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iretailer.report.base.BaseAction;
import com.iretailer.report.dto.PageResult;
import com.iretailer.report.dto.QueryOption;
import com.iretailer.report.dto.ReLocation;
import com.iretailer.report.model.Location;
import com.iretailer.report.model.User;
import com.iretailer.report.util.RMap;
import com.iretailer.report.util.SecurityUserUtil;
import com.iretailer.report.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Auther: xjw
 * @Date: 2019/1/25 16:49
 * @Description:
 */
@RestController
public class LocationController extends BaseAction {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/system/locationTree.action")
    public Map<String, Object> locationTree() {
        Location first = Location.FirstLocation;
        List<Location> locationTree = locationService.getLocationTree();
        first.setChildren(locationTree);
        return RMap.ok(new Location[]{first});
    }

    @RequestMapping("/system/gridLocation.action")
    public Map<String, Object> gridLocation(@RequestBody ReLocation reLocatoin) {
        QueryOption queryOption = modelMapper.map(reLocatoin, QueryOption.class);
        PageResult<Location> result = locationService.selectByParentIdPage(reLocatoin.getParentId(), queryOption);
        return RMap.ok(result);
    }

    @RequestMapping("/system/selectLocationById.action")
    public Map<String, Object> selectLocationById(@RequestBody ReLocation reLocatoin) {
        if (reLocatoin.getId().equals("-")) {
            return RMap.ok(Location.FirstLocation);
        } else {
            Location find = locationService.getById(reLocatoin.getId());
            return RMap.ok(find);
        }
    }

    @RequestMapping("/system/parentIdLocation.action")
    public Map<String, Object> parentIdLocation(@RequestBody ReLocation reLocation) {
        List<Location> result = locationService.list(new QueryWrapper<Location>().lambda()
                .eq(Location::getParentId, reLocation.getParentId())
                .orderByAsc(Location::getRanked));
        return RMap.ok(result);
    }

    @RequestMapping("/system/saveOrUpdateLocation.action")
    public Map<String, Object> saveOrUpdate(@RequestBody ReLocation reLocation, HttpServletRequest request) {
         User user = SecurityUserUtil.currentUser(request);
        Location location = modelMapper.map(reLocation, Location.class);
        boolean result = locationService.saveOrUpdate(location, user.getName());
        return RMap.resultBoolean(result);
    }

    @RequestMapping("/system/deleteLocation.action")
    public Map<String, Object> deleteLocation(@RequestBody List<String> ids) {
        boolean result = locationService.deleteByIds(ids);
        if (result) {
            return RMap.ok();
        } else {
            return RMap.error(RMap.Code.CONNECTED, "have_children_location");
        }
    }

    @RequestMapping("/system/findHefengLocation.action")
    public Map<String, Object> findHefengLocation(@RequestBody ReLocation reLocation) {
        String ak = "d6a177a1fb504906a3a8b86500ae6c66";
        if (StringUtil.notEmpty(reLocation.getApiKey())) {
            ak = reLocation.getApiKey();
        }
        String language = "zh-cn";
        if (StringUtil.notEmpty(reLocation.getWeatherLanguage())) {
            language = reLocation.getWeatherLanguage();
        }
        String template = "https://search.heweather.net/find?key={0}&lang={1}&location={2}";
        String url = MessageFormat.format(template, ak, language, reLocation.getLocation());
        String responeStr = restTemplate.getForObject(url, String.class);
        JSONObject heFengResult = JSON.parseObject(responeStr);
        JSONArray locations = heFengResult.getJSONArray("HeWeather6");
        if (locations.size() > 0) {
            JSONObject weatherResult = locations.getJSONObject(0);
            String status = weatherResult.getString("status");
            if (status.equals("ok")) {
                JSONArray basic = weatherResult.getJSONArray("basic");
                return RMap.ok(basic);
            }
        }
        return RMap.ok(Collections.emptyList());
    }

}

